package xman.mjava.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.nio.channels.SocketChannel;
import java.util.Random;

public class Client implements Runnable {
	private ByteBuffer buffer = ByteBuffer.allocate(8);
	private IntBuffer intBuffer = null;

	public Client() {
		intBuffer = buffer.asIntBuffer();
	}

	public int handler(int first, int second) throws Exception {
		int result = 0;
		SocketChannel sc = connect();
		try {
			sendSunRequest(sc, first, second);
			result = receiveResponse(sc);
		} finally {
			sc.close();
		}
		return result;
	}

	private int receiveResponse(SocketChannel sc) throws IOException {
		buffer.clear();
		sc.read(buffer);
		return intBuffer.get(0);
	}

	private void sendSunRequest(SocketChannel sc, int first, int second) throws IOException {
		buffer.clear();
		intBuffer.put(0, first);
		intBuffer.put(1, second);
		sc.write(buffer);
		System.out.println("send plus requestion: " + first + " + " + second + "-------------"
				+ Thread.currentThread().getName() + "-----------");
	}

	private SocketChannel connect() throws IOException {
		InetSocketAddress socketAddress = new InetSocketAddress("localhost", 1000);
		return SocketChannel.open(socketAddress);
	}

	public static void main(String[] args) {
		for (int i = 0; i < 50; i++) {
			Thread t = new Thread(new Client(), "t" + i);
			t.start();
			System.out.println("-----------------------" + i + "----------------------");
		}
	}

	@Override
	public void run() {
		Random randowm = new Random();
		synchronized (this) {
			try {
				System.out.println("plus result : " + handler(randowm.nextInt(), randowm.nextInt()) + "----------"
						+ Thread.currentThread().getName() + "--------------");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
